package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjProductImage;
import com.zb.mapper.ZjProductImageMapper;
import com.zb.service.ZjProductImageService;
import com.zb.vo.GoodsImageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 产品图片表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-08-15
 */
@Service
public class ZjProductImageServiceImpl extends ServiceImpl<ZjProductImageMapper, ZjProductImage> implements ZjProductImageService {

    // 新增、修改、删除产品图片
    @Override
    public void save(Long custAccId, Long productId, List<GoodsImageVo> imageVos, List<Long> delImageIds) {
        if (null != delImageIds && !delImageIds.isEmpty()) {
            this.removeByIds(delImageIds);
        }
        if (null == imageVos || imageVos.isEmpty()) {
            return;
        }
        List<ZjProductImage> adds = new ArrayList<>();
        List<ZjProductImage> updates = new ArrayList<>();
        ZjProductImage image = null;
        for (GoodsImageVo vo : imageVos) {
            image = new ZjProductImage();
            BeanUtils.copyProperties(vo, image);
            if (null != image.getId()) {
                updates.add(image);
                continue;
            }
            image.setId(IdWorker.getId());
            image.setCustAccId(custAccId);
            image.setProductId(productId);
            adds.add(image);
        }
        if (!adds.isEmpty()) this.saveBatch(adds);
        if (!updates.isEmpty()) this.updateBatchById(updates);
    }

    // 根据产品ID获取产品图片对象
    @Override
    public List<ZjProductImage> getByProductId(Long productId) {
        QueryWrapper<ZjProductImage> wrapper = new QueryWrapper<>();
        wrapper.select("id", "image");
        wrapper.eq("product_id", productId);
        return this.list(wrapper);
    }

    // 根据产品ID集合获取产品图片对象
    @Override
    public List<ZjProductImage> getByProductIds(List<Long> productIds) {
        if (null == productIds || productIds.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjProductImage> wrapper = new QueryWrapper<>();
        wrapper.select("id", "image");
        wrapper.in("product_id", productIds);
        return this.list(wrapper);
    }

    // 根据产品ID删除产品图片
    @Override
    public void deleteBatchByProductId(List<Long> productIds) {
        if (null == productIds || productIds.isEmpty()) {
            return;
        }
        QueryWrapper<ZjProductImage> wrapper = new QueryWrapper<>();
        wrapper.in("product_id", productIds);
        this.remove(wrapper);
    }
}
